//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package project_board_api_serv

import (
	"context"

	"atomgit.com/openlinksaas/api-server/api_common"
	"atomgit.com/openlinksaas/api-server/dao"
	"atomgit.com/openlinksaas/api-server/dao/project_board_dao"
	"atomgit.com/openlinksaas/api-server/dao/project_entry_dao"
	"atomgit.com/openlinksaas/api-server/utils"
	"atomgit.com/openlinksaas/proto-gen-go.git/notices/notices_board"
	"atomgit.com/openlinksaas/proto-gen-go.git/project_board_api"
	"go.mongodb.org/mongo-driver/mongo"
)

func (apiImpl *ProjectBoardApiImpl) CreateEdge(ctx context.Context, req *project_board_api.CreateEdgeRequest) (*project_board_api.CreateEdgeResponse, error) {
	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &project_board_api.CreateEdgeResponse{
			Code:   project_board_api.CreateEdgeResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	//检查权限
	projectItem, _, roleItem, err := utils.GetProjectMemberRole(ctx, req.ProjectId, sessionItem.UserId)
	if err == utils.ErrNoProject {
		return &project_board_api.CreateEdgeResponse{
			Code:   project_board_api.CreateEdgeResponse_CODE_NO_PROJECT,
			ErrMsg: "项目不存在",
		}, nil
	} else if err == utils.ErrNoRole {
		return &project_board_api.CreateEdgeResponse{
			Code:   project_board_api.CreateEdgeResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	} else if err != nil {
		return nil, err
	}
	entryItem, err := project_entry_dao.EntryDao.Get(ctx, req.BoardId, req.ProjectId)
	if err != nil {
		return &project_board_api.CreateEdgeResponse{
			Code:   project_board_api.CreateEdgeResponse_CODE_NO_BOARD,
			ErrMsg: "信息面板不存在",
		}, nil
	}

	canUpdate := api_common.CheckEntryCanUpdate(sessionItem, projectItem, roleItem, entryItem)
	if !canUpdate {
		return &project_board_api.CreateEdgeResponse{
			Code:   project_board_api.CreateEdgeResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}
	//检查节点是否存在
	exist, err := project_board_dao.NodeDao.Exist(ctx, req.ProjectId, req.BoardId, req.Edge.EdgeKey.FromNodeId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &project_board_api.CreateEdgeResponse{
			Code:   project_board_api.CreateEdgeResponse_CODE_NO_NODE,
			ErrMsg: "节点不存在",
		}, nil
	}
	exist, err = project_board_dao.NodeDao.Exist(ctx, req.ProjectId, req.BoardId, req.Edge.EdgeKey.ToNodeId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &project_board_api.CreateEdgeResponse{
			Code:   project_board_api.CreateEdgeResponse_CODE_NO_NODE,
			ErrMsg: "节点不存在",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = project_board_dao.EdgeDao.Insert(sessCtx, &project_board_dao.EdgeDbItem{
			BoardId:      req.BoardId,
			ProjectId:    req.ProjectId,
			FromNodeId:   req.Edge.EdgeKey.FromNodeId,
			FromHandleId: req.Edge.EdgeKey.FromHandleId,
			ToNodeId:     req.Edge.EdgeKey.ToNodeId,
			ToHandleId:   req.Edge.EdgeKey.ToHandleId,
			Label:        req.Edge.Label,
		})
		if err != nil {
			return nil, err
		}
		return &project_board_api.CreateEdgeResponse{
			Code: project_board_api.CreateEdgeResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	//发送通知
	go api_common.SendNoticeToProjectScope(context.Background(), req.ProjectId, &notices_board.CreateEdgeNotice{
		ProjectId:    req.ProjectId,
		BoardId:      req.BoardId,
		FromNodeId:   req.Edge.EdgeKey.FromNodeId,
		FromHandleId: req.Edge.EdgeKey.FromHandleId,
		ToNodeId:     req.Edge.EdgeKey.ToNodeId,
		ToHandleId:   req.Edge.EdgeKey.ToHandleId,
	})
	return ret.(*project_board_api.CreateEdgeResponse), nil
}

func (apiImpl *ProjectBoardApiImpl) RemoveEdge(ctx context.Context, req *project_board_api.RemoveEdgeRequest) (*project_board_api.RemoveEdgeResponse, error) {
	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &project_board_api.RemoveEdgeResponse{
			Code:   project_board_api.RemoveEdgeResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	//检查权限
	projectItem, _, roleItem, err := utils.GetProjectMemberRole(ctx, req.ProjectId, sessionItem.UserId)
	if err == utils.ErrNoProject {
		return &project_board_api.RemoveEdgeResponse{
			Code:   project_board_api.RemoveEdgeResponse_CODE_NO_PROJECT,
			ErrMsg: "项目不存在",
		}, nil
	} else if err == utils.ErrNoRole {
		return &project_board_api.RemoveEdgeResponse{
			Code:   project_board_api.RemoveEdgeResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	} else if err != nil {
		return nil, err
	}
	entryItem, err := project_entry_dao.EntryDao.Get(ctx, req.BoardId, req.ProjectId)
	if err != nil {
		return &project_board_api.RemoveEdgeResponse{
			Code:   project_board_api.RemoveEdgeResponse_CODE_NO_BOARD,
			ErrMsg: "信息面板不存在",
		}, nil
	}
	canUpdate := api_common.CheckEntryCanUpdate(sessionItem, projectItem, roleItem, entryItem)
	if !canUpdate {
		return &project_board_api.RemoveEdgeResponse{
			Code:   project_board_api.RemoveEdgeResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	exist, err := project_board_dao.EdgeDao.Exist(ctx, req.BoardId, req.EdgeKey.FromNodeId, req.EdgeKey.FromHandleId, req.EdgeKey.ToNodeId, req.EdgeKey.ToHandleId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &project_board_api.RemoveEdgeResponse{
			Code: project_board_api.RemoveEdgeResponse_CODE_OK,
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = project_board_dao.EdgeDao.Remove(sessCtx, req.BoardId, req.EdgeKey.FromNodeId, req.EdgeKey.FromHandleId, req.EdgeKey.ToNodeId, req.EdgeKey.ToHandleId)
		if err != nil {
			return nil, err
		}
		return &project_board_api.RemoveEdgeResponse{
			Code: project_board_api.RemoveEdgeResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	//发送通知
	go api_common.SendNoticeToProjectScope(context.Background(), req.ProjectId, &notices_board.RemoveEdgeNotice{
		ProjectId:    req.ProjectId,
		BoardId:      req.BoardId,
		FromNodeId:   req.EdgeKey.FromNodeId,
		FromHandleId: req.EdgeKey.FromHandleId,
		ToNodeId:     req.EdgeKey.ToNodeId,
		ToHandleId:   req.EdgeKey.ToHandleId,
	})
	return ret.(*project_board_api.RemoveEdgeResponse), nil
}

func (apiImpl *ProjectBoardApiImpl) UpdateEdge(ctx context.Context, req *project_board_api.UpdateEdgeRequest) (*project_board_api.UpdateEdgeResponse, error) {
	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &project_board_api.UpdateEdgeResponse{
			Code:   project_board_api.UpdateEdgeResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	//检查权限
	projectItem, _, roleItem, err := utils.GetProjectMemberRole(ctx, req.ProjectId, sessionItem.UserId)
	if err == utils.ErrNoProject {
		return &project_board_api.UpdateEdgeResponse{
			Code:   project_board_api.UpdateEdgeResponse_CODE_NO_PROJECT,
			ErrMsg: "项目不存在",
		}, nil
	} else if err == utils.ErrNoRole {
		return &project_board_api.UpdateEdgeResponse{
			Code:   project_board_api.UpdateEdgeResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	} else if err != nil {
		return nil, err
	}
	entryItem, err := project_entry_dao.EntryDao.Get(ctx, req.BoardId, req.ProjectId)
	if err != nil {
		return &project_board_api.UpdateEdgeResponse{
			Code:   project_board_api.UpdateEdgeResponse_CODE_NO_BOARD,
			ErrMsg: "信息面板不存在",
		}, nil
	}
	canUpdate := api_common.CheckEntryCanUpdate(sessionItem, projectItem, roleItem, entryItem)
	if !canUpdate {
		return &project_board_api.UpdateEdgeResponse{
			Code:   project_board_api.UpdateEdgeResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	exist, err := project_board_dao.EdgeDao.Exist(ctx, req.BoardId, req.Edge.EdgeKey.FromNodeId, req.Edge.EdgeKey.FromHandleId, req.Edge.EdgeKey.ToNodeId, req.Edge.EdgeKey.ToHandleId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &project_board_api.UpdateEdgeResponse{
			Code:   project_board_api.UpdateEdgeResponse_CODE_NO_EDGE,
			ErrMsg: "连接不存在",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = project_board_dao.EdgeDao.Update(sessCtx, req.BoardId, req.Edge.EdgeKey.FromNodeId, req.Edge.EdgeKey.FromHandleId, req.Edge.EdgeKey.ToNodeId, req.Edge.EdgeKey.ToHandleId,
			req.Edge.Label)
		if err != nil {
			return nil, err
		}
		return &project_board_api.UpdateEdgeResponse{
			Code: project_board_api.UpdateEdgeResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	//发送通知
	go api_common.SendNoticeToProjectScope(context.Background(), req.ProjectId, &notices_board.UpdateEdgeNotice{
		ProjectId:    req.ProjectId,
		BoardId:      req.BoardId,
		FromNodeId:   req.Edge.EdgeKey.FromNodeId,
		FromHandleId: req.Edge.EdgeKey.FromHandleId,
		ToNodeId:     req.Edge.EdgeKey.ToNodeId,
		ToHandleId:   req.Edge.EdgeKey.ToHandleId,
	})
	return ret.(*project_board_api.UpdateEdgeResponse), nil
}

func (apiImpl *ProjectBoardApiImpl) ListEdge(ctx context.Context, req *project_board_api.ListEdgeRequest) (*project_board_api.ListEdgeResponse, error) {
	emptyList := []*project_board_api.Edge{}

	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &project_board_api.ListEdgeResponse{
			Code:     project_board_api.ListEdgeResponse_CODE_WRONG_SESSION,
			ErrMsg:   "会话不存在",
			EdgeList: emptyList,
		}, nil
	}
	//检查权限
	_, _, _, err := utils.GetProjectMemberRole(ctx, req.ProjectId, sessionItem.UserId)
	if err == utils.ErrNoProject {
		return &project_board_api.ListEdgeResponse{
			Code:     project_board_api.ListEdgeResponse_CODE_NO_PROJECT,
			ErrMsg:   "项目不存在",
			EdgeList: emptyList,
		}, nil
	} else if err == utils.ErrNoRole {
		return &project_board_api.ListEdgeResponse{
			Code:     project_board_api.ListEdgeResponse_CODE_NO_PERMISSION,
			ErrMsg:   "没有权限",
			EdgeList: emptyList,
		}, nil
	} else if err != nil {
		return nil, err
	}

	edgeItemList, err := project_board_dao.EdgeDao.List(ctx, req.ProjectId, req.BoardId)
	if err != nil {
		return nil, err
	}

	edgeList := []*project_board_api.Edge{}
	for _, edgeItem := range edgeItemList {
		edgeList = append(edgeList, edgeItem.ToEdge())
	}
	return &project_board_api.ListEdgeResponse{
		Code:     project_board_api.ListEdgeResponse_CODE_OK,
		EdgeList: edgeList,
	}, nil
}

func (apiImpl *ProjectBoardApiImpl) GetEdge(ctx context.Context, req *project_board_api.GetEdgeRequest) (*project_board_api.GetEdgeResponse, error) {
	emptyEdge := &project_board_api.Edge{
		EdgeKey: &project_board_api.EdgeKey{},
	}

	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &project_board_api.GetEdgeResponse{
			Code:   project_board_api.GetEdgeResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
			Edge:   emptyEdge,
		}, nil
	}
	//检查权限
	_, _, _, err := utils.GetProjectMemberRole(ctx, req.ProjectId, sessionItem.UserId)
	if err == utils.ErrNoProject {
		return &project_board_api.GetEdgeResponse{
			Code:   project_board_api.GetEdgeResponse_CODE_NO_PROJECT,
			ErrMsg: "项目不存在",
			Edge:   emptyEdge,
		}, nil
	} else if err == utils.ErrNoRole {
		return &project_board_api.GetEdgeResponse{
			Code:   project_board_api.GetEdgeResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
			Edge:   emptyEdge,
		}, nil
	} else if err != nil {
		return nil, err
	}

	edgeItem, err := project_board_dao.EdgeDao.Get(ctx, req.BoardId, req.EdgeKey.FromNodeId, req.EdgeKey.FromHandleId, req.EdgeKey.ToNodeId, req.EdgeKey.ToHandleId)
	if err != nil {
		return &project_board_api.GetEdgeResponse{
			Code:   project_board_api.GetEdgeResponse_CODE_NO_EDGE,
			ErrMsg: "连接不存在",
			Edge:   emptyEdge,
		}, nil
	}
	return &project_board_api.GetEdgeResponse{
		Code: project_board_api.GetEdgeResponse_CODE_OK,
		Edge: edgeItem.ToEdge(),
	}, nil
}
